package com.netease.xone.fragment;

import preferMgr.XonePrefHelper;
import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.CheckVersionInfo;
import protocol.meta.HeadRecommend;
import Utils.XoneUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityInfoDetail;
import com.netease.xone.activity.ActivityLogin;
import com.netease.xone.activity.ActivityMain;
import com.netease.xone.activity.ActivityUpdateApp;
import com.netease.xone.widget.FlashTextView;
import com.netease.xone.widget.LoadingImageView;

public class FragmentTouTiao extends FragmentBase implements OnClickListener {
    private final String TAG = FragmentTouTiao.class.getSimpleName();
    public static final int MODE_INVALID = -1;
    public static final int MODE_FINISH = 0;

    private int mMode;
    private int mId = -1;
    private int mWidth;
    private int mHeight;
    private View mRootView;
    private GestureDetector mGestureDetector;
    private HeadRecommend mHeadRecommend;

    public static FragmentTouTiao newInstance(int mode) {
        FragmentTouTiao f = new FragmentTouTiao();
        Bundle b = new Bundle();
        b.putInt(XoneConsts.BUNDLE_KEY.TOUTIAO_MODE, mode);
        f.setArguments(b);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGestureDetector = new GestureDetector(new TouTiaoGestureListener());
        XoneService.getInstance().addListener(mXoneCallBack);
        mId = XoneService.getInstance().doHeadRecommend();
        mWidth = getResources().getDisplayMetrics().widthPixels;
        mHeight = getResources().getDisplayMetrics().heightPixels;
        mMode = getArguments().getInt(XoneConsts.BUNDLE_KEY.TOUTIAO_MODE, MODE_INVALID);
        new Handler().postDelayed(mMyRunnable, 100);
    }
    //检查版本
    private Runnable mMyRunnable = new Runnable() {
        @Override
        public void run() {
            XoneService.getInstance().doCheckAppVersion();
        } 
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        if (null == mRootView) {
            mRootView = inflater.inflate(R.layout.fragment_toutiao, container, false);
        }
        bindView(mRootView);

        return mRootView;
    }

    private void bindView(View view) {
        view.setOnTouchListener(new OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean bHandler = mGestureDetector.onTouchEvent(event);
                return bHandler;
            }});

        view.findViewById(R.id.linearLayout1).setOnClickListener(this);
        view.findViewById(R.id.linearLayout1).setVisibility(View.GONE);
        FlashTextView slide = (FlashTextView)view.findViewById(R.id.flash_text);
        slide.setShadowLayer(1, 0, -1, Color.BLACK);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
        mXoneCallBack = null;
        mRootView = null;
        mGestureDetector = null;
        mHeadRecommend = null;
    }

    @Override
    public void onClick(View v) {
        if (R.id.linearLayout1 == v.getId()) {
            if (null != mHeadRecommend && !TextUtils.isEmpty(mHeadRecommend.infoId)) {
                if (mMode == MODE_FINISH) {
                    ActivityInfoDetail.startActivity(getActivity(), mHeadRecommend.infoId, ActivityInfoDetail.MODE_FROM_INFO);
                } else {
                    ActivityInfoDetail.startActivity(getActivity(), mHeadRecommend.infoId, ActivityInfoDetail.MODE_FROM_TOUTIAO);
                }
            } else {
                ActivityMain.launch(getActivity());
            }
            
            getActivity().finish();
        }
    }

    class TouTiaoGestureListener implements OnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            int deltaX = (int)(e1.getX() - e2.getX());
            int deltaY = (int)(e1.getY() - e2.getY());
            /**
             * 头条滑动进入首页界面
             */
            if(Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0){
                getActivity().finish();
                if (mMode == MODE_FINISH) {
                    return true;
                }
                ActivityMain.launch(getActivity());
                return true;
            }
            return false;
        }

    }

    private void updateUI(HeadRecommend[] handRecommends) {
        if (null == handRecommends) {
            return;
        }
        
        //TODO 这里默认是第一个推荐
        mHeadRecommend = handRecommends[0];
        if (null == mHeadRecommend) {
            return;
        }
        
        mRootView.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
        String value = mHeadRecommend.imageUrl;
        LoadingImageView imageView = (LoadingImageView)mRootView.findViewById(R.id.imageView1);
        imageView.setServerClipSize(mWidth, mHeight);
        imageView.setLoadingImage(value);

        value = mHeadRecommend.title;
        ((TextView)mRootView.findViewById(R.id.title)).setText(value);

        value = mHeadRecommend.summary;
        ((TextView)mRootView.findViewById(R.id.summary)).setText(value);

    }

    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onHeadRecommend(int transactionId, Object obj) {
            if (mId == transactionId) {
                mId = -1;
                updateUI((HeadRecommend[])obj);
            }
        };

        @Override
        public void onHeadRecommendError(int transactionId, int errCode, String err) {
            if (mId == transactionId) {
                mId = -1;
            }
        };

        @Override
        public void onGetVersionInfo(int transactionId, CheckVersionInfo versionInfo) {
            if (versionInfo != null) {
                String curVersion = XoneUtil.getNumberVersion(getActivity());
                if (curVersion.compareToIgnoreCase(versionInfo.version) < 0) {
                    if (versionInfo.version.compareToIgnoreCase(XonePrefHelper
                            .getPreUpdateVersion(getActivity())) > 0) {
                        XonePrefHelper.putPreUpdateVersion(getActivity(), versionInfo.version);
                        ActivityUpdateApp.lunch(getActivity(), versionInfo.updateAddress,
                                versionInfo.description, versionInfo.version);
                    }
                }
            }
        };
        
        @Override
        public void onAccException(int transactionId, int errCode, String err) {
            ActivityLogin.launch(getActivity(), true, errCode);
        };       
    };
}
